﻿using System;
using System.Web;

namespace NotesFor
{
    public class ThumbnailHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string path = context.Request["path"].ToString();
            int maxSize = Convert.ToInt32(context.Request["size"]);
            int position = Convert.ToInt32(context.Request["pos"]);
            System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg;

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(context.Server.MapPath(path));
            System.IO.FileInfo fi = di.GetFiles()[position];
            switch (fi.Extension.ToLower())
            {
                case ".jpg":
                    format = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
                case ".gif":
                    format = System.Drawing.Imaging.ImageFormat.Gif;
                    break;
                case ".png":
                    format = System.Drawing.Imaging.ImageFormat.Png;
                    break;
            }

            System.Drawing.Image bmp = (System.Drawing.Image)System.Drawing.Image.FromFile(fi.FullName);
            System.Drawing.Image img = CreateThumbnail(bmp, maxSize);
            context.Response.ContentType = "image/jpeg";
            img.Save(context.Response.OutputStream, format);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private System.Drawing.Image CreateThumbnail(System.Drawing.Image src, int maxSize)
        {
            int w = src.Width;
            int h = src.Height;

            if (w > maxSize)
            {
                h = (h * maxSize) / w;
                w = maxSize;
            }

            if (h > maxSize)
            {
                w = (w * maxSize) / h;
                h = maxSize;
            }

            // The third parameter is required and is of type delegate.  Rather then create a method that
            // does nothing, .NET 2.0 allows for anonymous delegate (similar to anonymous functions in other languages).
            return src.GetThumbnailImage(w, h, delegate() { return false; }, IntPtr.Zero);
        }
    }
}
